import { login, isLogin } from '../../utils/login'
import { getAvatar } from '../../utils/getAvatar'
import { getTaskList } from '../../api/task'
import { getUserInfo } from '../../api/login'
import { assistantType, getAssistantList, getTopAssistantList } from '../../api/assistant';

Page({

  /**
   * 页面的初始数据
   */
  data: <any>{
    active: 0,
    content: '',
    list: [],
    topList: []
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }

    if (isLogin()) {
      this.init()
    }

    getTopAssistantList().then(res => {
      if(res?.rows){
        this.setData({
          topList: res.rows
        })
      }
    })
  },

  async init() {
    const userInfo = login()
    if (userInfo) {
      this.handleLoginAction(userInfo);
    }
    this.getInfo()
  },

  onLoad(){
    this.getList(this.data.active)
  },

  inputHandle(e: any){
    const value = e.detail.value;
    if(value === ''){
      this.setData({
        content: value
      })
      setTimeout(() => {
        this.getList(this.data.active)
      }, 0)
    }
  },

  searchHandle(e: any){
    const value = e.detail.value;
    this.setData({
      content: value
    })
    setTimeout(() => {
      this.getList(this.data.active)
    }, 0)
  },

  searchClick(){
    setTimeout(() => {
      this.getList(this.data.active)
    }, 100)
  },

  onSearchBlur(e: any){
    const value = e.detail.value;

    this.setData({
      content: value
    })
  },

  changeTabHandle(e: any){
    const { index } = e.currentTarget.dataset
    this.setData({
      active: index
    })
    this.getList(index)
  },

  getList(type: assistantType){
    getAssistantList({
      type,
      pageNum: 1,
      pageSize: 999,
      title: this.data.content
    }).then(res => {
      if(res?.rows){
        this.setData({
          list: res.rows
        })
      }
    })
  },

  enterAssistant(e) {
    const { assistant } = e.currentTarget.dataset
    console.log(assistant)
    
    wx.navigateTo({
      url: '/pages/chat/chat',
      events: {
        acceptDataFromOpenerPage: function (data: any) {
          console.log(data)
        }
      },
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          currentGuide: {
            ...assistant,
            ...assistant.modelVo,
            name: assistant.title
          }
        })
      }
    });
  },

  getInfo() {
    getUserInfo().then((res: any) => {
      let userInfo = res.user;
      if (userInfo) {
        wx.setStorageSync('userInfo', userInfo);
        this.handleLoginAction(userInfo)
      }
    })
  },


  getTaskHandle() {
    getTaskList().then(res => {
      const rows = res.rows?.map(item => {
        if (item.userList) {
          const userList = item.userList.map(user => {
            return {
              ...user,
              avatar: user.avatar || getApp().globalData.defaultAvatar
            }
          });
          return {
            ...item,
            userList
          }
        } else {
          return item;
        }
      })
      this.setData({
        taskList: rows
      })
    })
  },

  getAvatarHandle() {
    if (this.data.avatar) {
      return
    }
    const avatar = getAvatar(this)
    this.setData({
      avatar: avatar || getApp().globalData.defaultAvatar
    })
  },

  handleLoginAction(userInfo: any) {
    this.setData({
      userInfo: userInfo,
      logined: true,
      show: false
    })
  },


  // 跳转聊天
  chatRouter(number: number, voice_type: string) {
    wx.navigateTo({
      url: '/pages/chat/chat',
      events: {
        acceptDataFromOpenerPage: function (data: any) {
          console.log(data)
        }
      },
      success: (res) => {
        console.log("给语音的内容", this.data.chatdata[6])
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: this.data.chatdata[number], voice_type: voice_type })
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home`,
      "imageUrl": "/static/img/home.jpg"
    }
  },

  /**
   * 图片出错时，替换默认图片
   * @param e 
   */
  onError(e: any) {
    let { index, i } = e.currentTarget.dataset;
    let taskList = this.data.taskList;
    taskList[index].userList[i].avatar = getApp().globalData.defaultAvatar
    this.setData({
      taskList
    })
  },
})